﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KineticWebCrystalExport
{
    public partial class TxtConvert
    {

        /// <summary>
        /// 写入TXT文件
        /// </summary>
        /// <param name="strFileName">文件名称，包含扩展名</param>
        /// <param name="strFilePath">文件路径</param>
        /// <param name="bolAPP">是否往文件内追加内容True为是</param>
        /// <param name="strText">内容</param>
        /// <param name="EncodingType">编码</param>
        /// <returns></returns>
        public static void WriteToTxt(string strFileName, string strText, string strFilePath = @"D:\DebugLog", bool bolAPP = true, string EncodingType = "")
        {
            try
            {
                if (strFilePath.EndsWith(@"\"))
                { strFilePath = strFilePath.Substring(0, strFilePath.Length - 1); }
                if (strFileName != "" && strFileName.EndsWith(@".txt") == false)
                { strFileName += ".txt"; }
                if (strFileName == "")
                {
                    strFilePath = strFilePath + $@"\DebugLog{DateTime.Now.ToString("yyyy-MM-dd")}.txt";
                }
                else
                {
                    strFilePath = strFilePath + @"\" + strFileName;
                }
                if (strFilePath.IndexOf(".") > 0)
                {
                    if (!File.Exists(strFilePath))
                    {
                        char[] separator = new char[] { '\\' };
                        string[] strArray = strFilePath.Split(separator);
                        int index = strFilePath.IndexOf(strArray[strArray.Length - 1].ToString());
                        string path = strFilePath.Substring(0, index);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        FileStream stream = File.Create(strFilePath);
                        byte[] bytes = Encoding.Default.GetBytes(" ".ToCharArray());
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Close();
                        stream = null;
                    }
                    StreamWriter writer = new StreamWriter(strFilePath, bolAPP, (EncodingType == "ASCII") ? Encoding.ASCII : Encoding.UTF8);
                    writer.WriteLine($"【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}】"+strText);
                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                WriteToTxt("", "【" + System.Reflection.MethodBase.GetCurrentMethod().Name + "】" + ex.Message);
            }
        }
    }
}
